package com.liuya.shiro;

import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liuya.common.CookieUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * @Author 刘亚
 * @Date 2016/12/15
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
    private static final String token = "token";
    private static final String badMes = "Bad or missing token!";

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws IOException {
        String cookie = CookieUtils.getCookie(request, token);
        if (request.getMethod().equalsIgnoreCase("POST")) {
            String header = request.getHeader("X-Requested-With");
            if (header != null && header.equalsIgnoreCase("XMLHttpRequest")) {
                if (cookie != null && cookie.equals(request.getHeader(token)))
                    return true;
                response.addHeader("tokenStatus", "accessDenied");
            } else if (cookie != null && cookie.equals(request.getParameter(token))) {
                return true;
            }
            if (cookie == null) {
                cookie = UUID.randomUUID().toString();
                CookieUtils.addCookie(request, response, token, cookie);
            }
            response.sendError(403, badMes);
            return false;
        }
        if (cookie == null) {
            cookie = UUID.randomUUID().toString();
            CookieUtils.addCookie(request, response, token, cookie);
        }
        request.setAttribute(token, cookie);
        return true;
    }
}